<template>
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
        <el-form-item prop="username">
            <el-input v-model="loginForm.username" :placeholder="$t('login.username')+'：admin'">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <user />
                    </el-icon>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" :placeholder="$t('login.password')+'：123456'" show-password autocomplete="new-password">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <lock />
                    </el-icon>
                </template>
            </el-input>
        </el-form-item>
    </el-form>
    <div class="login-btn">
        <el-button icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> {{ $t("login.reset") }} </el-button>
        <el-button icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> {{$t("login.login")}} </el-button>
    </div>
</template>
<script setup lang="ts">
import { loginApi } from "@/api/modules";
import { getTimeState } from "@/utils";
import { HOME_URL } from "@/config/config";
import type { ElForm } from "element-plus";
import { useUserStore, useTabStore, useKeepAliveStore } from "@/store/modules";
import { initDynamicRouter } from "@/router/modules/dynamicRouter";
import md5 from "md5";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();

const loading = ref(false);
const loginForm = reactive({
    username: "admin",
    password: "admin",
});
const loginRules = reactive({
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const login = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (!valid) return;
        loading.value = true;
        try {
            // 登录
            const { data } = await loginApi({
                ...loginForm,
                password: md5(loginForm.password),
            });
            userStore.setToken(data.access_token);

            // 2.添加动态路由
            await initDynamicRouter();

            // 3.清空 tabs、keepAlive 数据
            tabsStore.setTabs([]);
            keepAliveStore.setKeepAliveName([]);

            // 4.跳转到首页
            router.push(HOME_URL);
            ElNotification({
                title: getTimeState(),
                message: "欢迎登录",
                type: "success",
                duration: 3000,
            });
        } finally {
            loading.value = false;
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    Object.assign(loginForm, { username: "", password: "" });
};

onMounted(() => {
    document.onkeydown = (e: KeyboardEvent) => {
        if (
            e.code === "Enter" ||
            e.code === "enter" ||
            e.code === "NumpadEnter"
        ) {
            if (loading.value) return;
            login(loginFormRef.value);
        }
    };
});

onUnmounted(() => {
    document.onkeydown = null;
});
</script>
<style scoped lang="scss">
@import "../index.scss";
</style>
